package com.ptswitch.material.service.impl;

import org.hibernate.Hibernate;
import org.hxzon.project.AbstractModelService;
import org.hxzon.util.BitUtil;
import org.hxzon.util.StringUtil;
import org.springframework.stereotype.Service;

import com.ptswitch.material.model.material.Bom;
import com.ptswitch.material.service.BomService;

@Service
public class BomServiceImpl extends AbstractModelService<Bom> implements BomService {

    public void deleteAll() {
        // dao.deleteAll(Bom.class);
        for (Bom bom : dao.findAll(Bom.class)) {
            dao.delete(bom);
        }
    }

    public Bom findById(String id, int init) {
        Bom bom = dao.findById(Bom.class, id);
        if (bom != null) {
            if (BitUtil.isSet(init, Init_BomMaterials)) {
                Hibernate.initialize(bom.getBomMaterials());
            }
        }
        return bom;
    }

    public Bom findByCodeAndVersion(String code, String version) {
        code = StringUtil.escapeSql(code);
        version = StringUtil.escapeSql(version);
        return dao.findOne(Bom.class, " where p.code='" + code + "' and p.version='" + version + "'");
    }

    // public List<Bom> findAll(boolean initialize) {
    // List<Bom> list = dao.findAll(Bom.class, -1, -1,
    // " order by p.code asc,p.version desc");
    // if (initialize) {
    // for (Bom bom : list) {
    // Hibernate.initialize(bom.getBomMaterials());
    // }
    // }
    // return list;
    // }

    public void update(Bom oldModel, Bom newModel) {
        //FIXME bom materials and upload delete cascade
        // dao.deleteAll(oldModel.getBomMaterials());
        dao.delete(oldModel);
        // dao.delete(oldModel.getUpload());
        // add new
        dao.save(newModel.getOrigFile());
        dao.save(newModel);
        // newModel.getUpload().setOwnerId(newModel.getId());
        // newModel.getUpload().setOwnerType("bomSource");
        dao.saveAll(newModel.getBomMaterials());
    }

    public void saveEx(Bom model) {
        dao.save(model.getOrigFile());
        dao.save(model);
//		model.getUpload().setCreateTime(DateUtil.formatToNano(new Date()));
        // model.getUpload().setOwnerType("bomSource");
        // model.getUpload().setOwnerId(model.getId());
        dao.saveAll(model.getBomMaterials());
    }

    public String valid(Bom model) {
        String error = "";
        if (model.getCode() == null || model.getCode().isEmpty()) {
            error += "编码不能为空";
        }
        if (model.getVersion() == null || model.getVersion().isEmpty()) {
            error += "版本号不能为空";
        }
        return error;
    }

}
